package com.example.activity;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.TextView;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class SendDataActivity extends AppCompatActivity implements View.OnClickListener {
    private static ActivityResultLauncher<Intent> register;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_data);
        findViewById(R.id.bt_send).setOnClickListener(this);

        // 当下一个页面关闭后，将会调用此方法，必须在onCreate方法中创建（需要获取返回结果时使用）
        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                Intent intent = result.getData();
                if (intent != null && result.getResultCode() == Activity.RESULT_OK) {
                    Bundle bundle = intent.getExtras();
                    TextView textView = findViewById(R.id.tv_send);
                    textView.setText(bundle.getString("sender") + ":\n" + bundle.getString("data"));
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.CHINA);
        Intent intent = new Intent(this, ReceiveDataActivity.class);
        // 创建bundle
        Bundle bundle = new Bundle();
        // 存放数据，以key-value的形式存在
        bundle.putString("sender", this.getPackageName() + "." + this.getLocalClassName());
        bundle.putString("data", formatter.format(date));
        // 放入intent
        intent.putExtras(bundle);
        // 执行，不需要返回结果的话可以直接startActivity(intent)
        register.launch(intent);
    }
}
